package com.yy.jhl.app;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.yy.common.commonutils.DownFileUtil;
import com.yy.common.commonutils.FileUtil;
import com.yy.common.commonutils.NetWorkUtils;
import com.yy.common.commonutils.StringUtil;
import com.yy.common.commonutils.ToastUitl;
import com.yy.jhl.util.Configuration;

import java.io.File;

/**
 * Created by Ellis.Li on 2017/7/10.
 */

public class DownService extends Service {
    String fileUrl = "";
    boolean isDowning = false;
    public DownService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        fileUrl = intent.getStringExtra("fileUrl");
        downLoadAPK(fileUrl);
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * apk下载
     * @param fileUrl
     */
    private void downLoadAPK(String fileUrl){
        if (!NetWorkUtils.isNetConnected(DownService.this)){
            ToastUitl.showShort(getString(com.yy.common.R.string.no_net));
            return;
        }
        if (isDowning){
            ToastUitl.showShort("正在下载中，请勿重复点击...");
            return;
        }
        if (StringUtil.isEmpty(fileUrl)){
            ToastUitl.showShort("下载链接不能为空");
            return;
        }
        String fileToPath = Configuration.getInstallDirectoryPath()+"tracePro.apk";
        if (FileUtil.fileIsExists(fileToPath)){
            FileUtil.deleteFile(fileToPath);
        }
        DownFileUtil.getInstance().downFile(fileUrl, fileToPath, new DownFileUtil.FileDownInterface() {
            @Override
            public void start() {
                isDowning = true;
                ToastUitl.showShort("正在为您下载最新版本，请稍后...");
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {

            }

            @Override
            public void onSuccess(File file) {
                stopSelf();
                FileUtil.installApk(MyApplication.getAppContext(),file);
            }

            @Override
            public void onFailure(String errorStr) {
                stopSelf();
                ToastUitl.showShort("文件下载失败，请重新点击下载...");
            }
        });
    }
    private void stop(){
        isDowning = false;
        stopSelf();
    }
}
